using MapsterMapper;
using AiQiuQuan.Sport.Model.Models;
using AiQiuQuan.Sport.WebApi.Repositories;
using AiQiuQuan.Sport.Core;
using AiQiuQuan.Sport.WebApi.Entities;
using Microsoft.EntityFrameworkCore;
using AiQiuQuan.Sport.WebApi.Core;
using AiQiuQuan.Sport.Model.Enums;

namespace AiQiuQuan.Sport.WebApi.Services.Impl
{
    /// <summary>
    /// 场馆会员卡套管理
    /// </summary>
    public class VenueMemberCardService : IVenueMemberCardService
    {
        private readonly IMapper _mapper;
        private readonly IVenueMemberCardRepository _venueMemberCardRepository;
        private readonly IVenueInfoRepository _venueInfoRepository;
        private readonly IBaseUserRepository _baseUserRepository;
        private readonly IBaseUserVenueInfoRelationRepository _venueInfoRelationRepository;
        private readonly ICurrentInfo _currentInfo;

        /// <summary>
        /// ctor
        /// </summary>
        public VenueMemberCardService(
            IMapper mapper,
            ICurrentInfo currentInfo,
            IUnitOfWorkManager unitOfWorkManager,
            IVenueMemberCardRepository venueMemberCardRepository,
            IVenueInfoRepository venueInfoRepository,
            IBaseUserRepository baseUserRepository,
            IBaseUserVenueInfoRelationRepository venueInfoRelationRepository)
        {
            _mapper = mapper;
            _currentInfo = currentInfo;
            _venueMemberCardRepository = venueMemberCardRepository;
            _venueInfoRepository = venueInfoRepository;
            _baseUserRepository = baseUserRepository;
            _venueInfoRelationRepository = venueInfoRelationRepository;
        }

        /// <summary>
        /// 查询一条记录
        /// </summary>
        public async Task<VenueMemberCardDto> GetAsync(Guid id)
        {
            var venueMemberCard = await _venueMemberCardRepository.FirstOrDefaultAsync(m => m.ID == id);
            if (venueMemberCard == null)
            {
                return null;
            }

            var result = _mapper.Map<VenueMemberCard, VenueMemberCardDto>(venueMemberCard);
            var venue = await _venueInfoRepository.FirstOrDefaultAsync(m => m.ID == venueMemberCard.VenueId);
            result.VenueName = venue == null ? string.Empty : venue.VI_Name;

            return result;
        }

        /// <summary>
        /// 分页请求
        /// </summary>
        public async Task<PageResult<VenueMemberCardDto>> PageListAsync(VenueMemberCardPageRequestDto request)
        {
            var queryable = from venueCard in _venueMemberCardRepository.AsNoTracking()
                            join venue in _venueInfoRepository.AsNoTracking()
                            on venueCard.VenueId equals venue.ID
                            select new VenueMemberCardDto
                            {
                                ID = venueCard.ID,
                                Name = venueCard.Name,
                                CardType = venueCard.CardType,
                                SiteType = venueCard.SiteType,
                                State = venueCard.State,
                                VenueId = venueCard.VenueId,
                                AvailableDate = venueCard.AvailableDate,
                                ValidMonth = venueCard.ValidMonth,
                                StartTime = venueCard.StartTime,
                                EndTime = venueCard.EndTime,
                                Remark = venueCard.Remark,
                                CreateTime = venueCard.CreateTime,
                                VenueName = venue.VI_Name
                            };
            if (request.VenueId.HasValue)
            {
                queryable = queryable.Where(m => m.VenueId == request.VenueId.Value);
            }

            if (request.CardType.HasValue)
            {
                queryable = queryable.Where(m => m.CardType == request.CardType.Value);
            }

            if (request.IsOnlySale.HasValue && request.IsOnlySale.Value)
            {
                queryable = queryable.Where(m => m.State == MemberCardStatusEnum.Normal);
            }
            else
            {
                if (request.State.HasValue)
                {
                    queryable = queryable.Where(m => m.State == request.State.Value);
                }
            }

            var pageResult = await queryable.OrderBy(m => m.CreateTime).PageListAsync(request);
            return pageResult;
        }

        /// <summary>
        /// 新增
        /// </summary>
        public async Task<UnaryResult> AddAsync(VenueMemberCardAddDto model)
        {
            var venue = await _venueInfoRepository.FirstOrDefaultAsync(m => m.ID == model.VenueId);
            if (venue == null)
            {
                return UnaryResult.Faild(10, "场馆不存在");
            }

            var user = await _baseUserRepository.FirstOrDefaultAsync(m => m.U_OpenId == _currentInfo.MiniProgramOpenId);
            if (user == null)
            {
                return UnaryResult.Faild(10, "未获取到用户信息");
            }

            var userVenue = await _venueInfoRelationRepository.FirstOrDefaultAsync(m => m.BaseUserID == user.ID && m.VenueInfoID == model.VenueId);
            if (userVenue == null)
            {
                return UnaryResult.Faild(10, "当前登录用户不是此场馆管理员");
            }

            if (await _venueMemberCardRepository.AnyAsync(m => m.VenueId == model.VenueId && m.Name == model.Name))
            {
                return UnaryResult.Faild(10, "场馆会员卡名称重复");
            }

            var venueMemberCard = _mapper.Map<VenueMemberCard>(model);
            venueMemberCard.State = Model.Enums.MemberCardStatusEnum.Normal;
            venueMemberCard.SiteType = model.SiteTypeList.ListToString();
            venueMemberCard.AvailableDate = model.AvailableDateList.ListToString();
            await _venueMemberCardRepository.AddAsync(venueMemberCard);

            return UnaryResult.Succeed();
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        public async Task<UnaryResult> UpdateStateAsync(VenueMemberCardUpdateStatusDto model)
        {
            var venueMemberCard = await _venueMemberCardRepository.FirstOrDefaultAsync(m => m.ID == model.Id);
            if (venueMemberCard == null)
            {
                return UnaryResult.Faild(10, "场馆卡套数据未找到");
            }

            var user = await _baseUserRepository.FirstOrDefaultAsync(m => m.U_OpenId == _currentInfo.MiniProgramOpenId);
            if (user == null)
            {
                return UnaryResult.Faild(10, "未获取到用户信息");
            }

            var userVenue = await _venueInfoRelationRepository.FirstOrDefaultAsync(m => m.BaseUserID == user.ID && m.VenueInfoID == venueMemberCard.VenueId);
            if (userVenue == null)
            {
                return UnaryResult.Faild(10, "当前登录用户不是此场馆管理员");
            }

            venueMemberCard.State = model.State;
            await _venueMemberCardRepository.UpdateAsync(venueMemberCard);

            return UnaryResult.Succeed();
        }

        /// <summary>
        /// 卡套编辑
        /// </summary>
        public async Task<UnaryResult> UpdateAsync(VenueMemberCardUpdateDto model)
        {
            var venueMemberCard = await _venueMemberCardRepository.FirstOrDefaultAsync(m => m.ID == model.ID);
            if (venueMemberCard == null)
            {
                return UnaryResult.Faild(10, "场馆卡套数据未找到");
            }

            venueMemberCard.Remark = model.Remark ?? string.Empty;
            venueMemberCard.Name = model.Name;
            await _venueMemberCardRepository.UpdateAsync(venueMemberCard);
            return UnaryResult.Succeed();
        }
    }
}